﻿using System.Collections.Generic;

namespace Framework
{
    public class ObjectPool<T> where T : IPoolable, new()
    {
        private Stack<T> _objectStack = new Stack<T>();
        
        public T Retain(params object[] args)
        {
            T poolable;
            if (_objectStack.Count > 0)
            {
                poolable = _objectStack.Pop();
            }
            else
            {
                poolable = new T();
            }
            poolable.Retain(args);
            return poolable;
        }
        
        public void Release(T poolable)
        {
            poolable.Release();
            _objectStack.Push(poolable);
        }

        public void RemoveAll()
        {
            while (_objectStack.Count > 0)
            {
                T poolable = _objectStack.Pop();
                poolable.Dispose();
            }
        }
    }
}